package com.sanno.report.controller;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.yulichang.query.MPJQueryWrapper;
import com.sanno.common.entity.*;
import com.sanno.common.result.Result;
import com.sanno.report.dao.MedicalResultMapper;
import com.sanno.report.dao.PatientMapper;
import com.sanno.report.dao.ReportList;
import com.sanno.report.dao.StoreMapper;
import com.sanno.report.util.RedisUtil;
import com.sanno.report.vo.*;
import org.apache.ibatis.annotations.Select;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.lang.invoke.ConstantCallSite;
import java.text.ParseException;
import java.util.*;

@RestController
@RequestMapping("/Report")
@CrossOrigin
public class ReportController {
    @Resource
    private PatientMapper patientMapper;
    @Resource
    private MedicalResultMapper medicalResultMapper;
    @Resource
    private StoreMapper storeMapper;
    @Resource
    private ReportList reportList;

    @Resource
    private RedisUtil redisUtil;
    @RequestMapping("reportlist")
    public Result reportlist(String searchParams, Integer page, Integer limit) throws JsonProcessingException {
        SccPatient sccPatient = new SccPatient();
        if (searchParams!=null) {
            ObjectMapper objectMapper = new ObjectMapper();
            sccPatient = objectMapper.readValue(searchParams, SccPatient.class);
        }
        MPJQueryWrapper<SccPatient> mpjQueryWrapper=new MPJQueryWrapper();
        mpjQueryWrapper.selectAll(SccPatient.class);
        mpjQueryWrapper.select("Store.store_name");
        mpjQueryWrapper.leftJoin("scc_drugstore Store on t.patient_drugstore=Store.Store_id");
        if (!Objects.equals(sccPatient.getName(), "")&&sccPatient.getName()!=null){
            mpjQueryWrapper.like("t.Name",sccPatient.getName());
        }else if(!Objects.equals(sccPatient.getPhone(), "")&&sccPatient.getPhone()!=null){
            mpjQueryWrapper.like("t.phone",sccPatient.getPhone());
        }else if (!Objects.equals(sccPatient.getStoreName(), "")&&sccPatient.getStoreName()!=null){
            mpjQueryWrapper.like("Store.Store_name",sccPatient.getStoreName());
        }
        IPage<SccPatient> sccPatientIPage = patientMapper.selectJoinPage(new Page<SccPatient>(page, limit), SccPatient.class,
                mpjQueryWrapper
        );
        System.out.println(sccPatientIPage.getRecords());
        return Result.ok(sccPatientIPage.getRecords(),sccPatientIPage.getTotal());
    }
    @RequestMapping("reportPatient")
    public Result reportPatient(String searchParams) throws JsonProcessingException, ParseException {
        ObjectMapper objectMapper = new ObjectMapper();
        ReportVo reportVo = objectMapper.readValue(searchParams,ReportVo.class);
        System.out.println(reportVo);
        QueryWrapper<SccMedicalResult> queryWrapper=new QueryWrapper<SccMedicalResult>();
        queryWrapper.eq("Patient_id",reportVo.getPid());
        if (!Objects.equals(reportVo.getDrugstoreId(), "")){
            queryWrapper.eq("drugstore_id",reportVo.getDrugstoreId());
        }
        queryWrapper.lt("Test_time",new Date());
        queryWrapper.gt(" Test_time",reportVo.getTestTime());
        List<SccMedicalResult> sccMedicalResults = medicalResultMapper.selectList(queryWrapper);
        ArrayList<ReportVo1>  arrs = new ArrayList<>();
        for (SccMedicalResult sccMedicalResult : sccMedicalResults) {
            ReportVo1 reportVo1=new ReportVo1();
            Double[] arr1=new Double[]{sccMedicalResult.getGluResult(),
                    sccMedicalResult.getHbaicResult(),
                    sccMedicalResult.getUaResult(),
                    sccMedicalResult.getHdiCResult(),
                    sccMedicalResult.getLdlCResult(),
                    sccMedicalResult.getTgResult(),
                    sccMedicalResult.getCholResult(),
                    sccMedicalResult.getTcHdiCResult(),
                    sccMedicalResult.getKetResult(),
                    sccMedicalResult.getSbpResult(),
                    sccMedicalResult.getDbpResult()
                };
            reportVo1.setArr(arr1);

            String substring = sccMedicalResult.getTestTime().toString().substring(0, 9);
            reportVo1.setTime(sccMedicalResult.getTestTime());
            arrs.add(reportVo1);
        }

        return Result.ok(arrs);
    }

    @RequestMapping(value = "getStore",method = RequestMethod.GET)
    public Result getStore(){
        String key=ReportController.class.getPackage().getName()+Thread.currentThread() .getStackTrace()[1].getMethodName();
        System.out.println(key+"2222222222");
        if (redisUtil.get(key)==null){
            QueryWrapper queryWrapper = new QueryWrapper<SccDrugstore>();
            queryWrapper.select("Store_name","Store_id");
            List list = storeMapper.selectList(queryWrapper);
            System.out.println(list);
            redisUtil.set(key,list);
            return Result.ok(list);
        }else {
            return Result.ok(redisUtil.get(key));
        }

    }

    @RequestMapping(value = "abnormal")
    public Result getAbnormal(AbnormalVo1 abnormalVo1){
        System.out.println(abnormalVo1);
        MPJQueryWrapper<SccReportList> queryWrapper = new MPJQueryWrapper<SccReportList>();
        queryWrapper.rightJoin("scc_medical_result a on a.Result_id=t.Result_id");
        queryWrapper.leftJoin("scc_patient b on b.Patient_id=a.Patient_id");
        queryWrapper.eq("year(t.Update_time)",abnormalVo1.getStartTime());
        queryWrapper.select("DATE_FORMAT(t.Update_time,'%m') mun");
        queryWrapper.groupBy("mun");
        AbnormalVo2 abnormalVo2=new AbnormalVo2();
        ArrayList<String>arrayList=new ArrayList();
        ArrayList<String[]>arrayList1=new ArrayList();
        if (!Objects.equals(abnormalVo1.getIndex(), "")){
            queryWrapper.eq("t.Medical_name",abnormalVo1.getIndex());
        }
        if (!Objects.equals(abnormalVo1.getStore(), "")){
            queryWrapper.eq("a.drugstore_id",abnormalVo1.getStore());
        }
        if ( abnormalVo1.getSex()!=null && abnormalVo1.getSex().equals("男") ){
            queryWrapper.select("COUNT(*) as man");
            queryWrapper.eq("b.sex",1);
            List<Map<String, Object>> maps = reportList.selectJoinMaps(queryWrapper);
            System.out.println(maps);
            for (Map<String, Object> map : maps) {
                String[] arr =new String[4];
                int i=0;
                for(String key:map.keySet()){//keySet获取map集合key的集合  然后在遍历key即可
                    String value = map.get(key).toString();//
                    switch (key) {
                        case "mun":
                            arr[0] = value + "月";
                            break;
                        case "man":
                            arr[1] = value;
                            break;
                        case "woman":
                            arr[2] = value;
                            break;
                        case "quan":
                            arr[3] = value;
                            break;
                    }
                }

                arrayList1.add(arr);
            }
            System.out.println(arrayList1);
            abnormalVo2.setQuan(arrayList1);

            abnormalVo2.setName(new String[]{"product","男"});
            return Result.ok(abnormalVo2);
        }else if (abnormalVo1.getSex()!=null && abnormalVo1.getSex().equals("女")){
            queryWrapper.select("COUNT(*) as woman");
            queryWrapper.eq("b.sex",0);
            List<Map<String, Object>> maps = reportList.selectJoinMaps(queryWrapper);
            System.out.println(maps);
            for (Map<String, Object> map : maps) {
                String[] arr =new String[4];
                int i=0;
                for(String key:map.keySet()){//keySet获取map集合key的集合  然后在遍历key即可
                    String value = map.get(key).toString();//
                    switch (key) {
                        case "mun":
                            arr[0] = value + "月";
                            break;
                        case "man":
                            arr[1] = value;
                            break;
                        case "woman":
                            arr[2] = value;
                            break;
                        case "quan":
                            arr[3] = value;
                            break;
                    }
                }

                arrayList1.add(arr);
            }
            abnormalVo2.setQuan(arrayList1);
            abnormalVo2.setName(new String[]{"product","女"});
            return Result.ok(abnormalVo2);
        }
        queryWrapper.select("count(t.id) quan,sum(case when b.Sex='1' then 1 else 0 end ) man,sum(case when b.Sex='0' then 1 else 0 end ) woman");



        List<Map<String, Object>> maps = reportList.selectJoinMaps(queryWrapper);
        System.out.println(maps);
        for (Map<String, Object> map : maps) {
            String[] arr =new String[4];
            int i=0;
            for(String key:map.keySet()){//keySet获取map集合key的集合  然后在遍历key即可
                String value = map.get(key).toString();//
                switch (key) {
                    case "mun":
                        arr[0] = value + "月";
                        break;
                    case "man":
                        arr[1] = value;
                        break;
                    case "woman":
                        arr[2] = value;
                        break;
                    case "quan":
                        arr[3] = value;
                        break;
                }
            }
            arrayList1.add(arr);
        }
        System.out.println(arrayList1);
        abnormalVo2.setQuan(arrayList1);
        abnormalVo2.setName(new String[]{"product","男","女","合计"});

        return Result.ok(abnormalVo2);
    }

    @RequestMapping("consumer")
    public Result consumer(Consumer consumer){
        MPJQueryWrapper<SccReportList> jQueryWrapper = new MPJQueryWrapper<>();
        jQueryWrapper.select("AVG(DISTINCT b.age) as avg,COUNT(DISTINCT b.Patient_id) people,COUNT(t.id) abnormalPeople");
        jQueryWrapper.leftJoin("scc_medical_result a on a.Result_id=t.Result_id");
        jQueryWrapper.rightJoin("scc_patient b on b.Patient_id=a.Patient_id");
        jQueryWrapper.lt("a.Test_time",new Date());
        jQueryWrapper.gt("a.Test_time",consumer.getTime());
        ConsumerVo1 consumerVo1 = reportList.selectJoinOne(ConsumerVo1.class, jQueryWrapper);
        MPJQueryWrapper<SccReportList> jQueryWrapper1 = new MPJQueryWrapper<>();
        jQueryWrapper.leftJoin("scc_medical_result a on a.Result_id=t.Result_id");
        jQueryWrapper.rightJoin("scc_patient b on b.Patient_id=a.Patient_id");
        jQueryWrapper1.ne("t.Medical_status","0");
        Integer integer = reportList.selectJoinCount(jQueryWrapper1);
        System.out.println(integer);
        consumerVo1.setAbnormalPeople(consumerVo1.getAbnormalPeople()/integer*100);
        return Result.ok(consumerVo1);
    }
    @RequestMapping("consumerlist")
    public Result consumerlist(Consumer consumer){
        MPJQueryWrapper<SccReportList> jQueryWrapper = new MPJQueryWrapper<>();
        jQueryWrapper.select("DATE_FORMAT(t.Update_time,'%m') mun,COUNT(DISTINCT b.Patient_id) as count");
        jQueryWrapper.leftJoin("scc_medical_result a on a.Result_id=t.Result_id");
        jQueryWrapper.rightJoin("scc_patient b on b.Patient_id=a.Patient_id");
        jQueryWrapper.lt("a.Test_time",new Date());
        jQueryWrapper.gt("a.Test_time",consumer.getTime());

        jQueryWrapper.groupBy("mun");
        List<Map<String, Object>> maps = reportList.selectJoinMaps(jQueryWrapper);
        ConsumerVo2 consumerVo2=new ConsumerVo2();
        ArrayList<String> list1=new ArrayList<String>();
        ArrayList<String> list2=new ArrayList<String>();
        for (Map<String, Object> map : maps) {
            for (String key: map.keySet()
                 ) {
                String value = map.get(key).toString();//
                if (key.equals("mun")){
                    list1.add(value);
                }else {
                    list2.add(value);
                }
            }
        }
        consumerVo2.setArr1(list1.toArray());
        consumerVo2.setArr2(list2.toArray());

        return Result.ok(consumerVo2);
    }
    @RequestMapping("record")
    public Result recordList(String searchParams,Integer page, Integer limit) throws JsonProcessingException {
        MPJQueryWrapper<SccMedicalResult> jQueryWrapper = new MPJQueryWrapper<>();
        jQueryWrapper.selectAll(SccMedicalResult.class);
        jQueryWrapper.select("pa.name,pa.Age,pa.Weight,pa.Height,pa.Count_of_test,pa.Phone,CONCAT(t.Sbp_result,'/',t.Dbp_result) as xueYa");
        jQueryWrapper.leftJoin("scc_patient pa on pa.Patient_id=t.Patient_id");
        if (searchParams==null) {
            IPage<SccMedicalResult> sccMedicalResultIPage = medicalResultMapper.selectJoinPage(new Page<>(page, limit), SccMedicalResult.class, jQueryWrapper);
            return Result.ok(sccMedicalResultIPage.getRecords(),sccMedicalResultIPage.getTotal());
        }
        SccDrugstore sccDrugstore=new SccDrugstore();
        ObjectMapper objectMapper = new ObjectMapper();
        sccDrugstore = objectMapper.readValue(searchParams, SccDrugstore.class);
        jQueryWrapper.rightJoin("scc_drugstore a on a.Store_id=t.drugstore_id");
        jQueryWrapper.eq("a.Store_name",sccDrugstore.getStoreName());
        IPage<SccMedicalResult> sccMedicalResultIPage = medicalResultMapper.selectJoinPage(new Page<>(page, limit), SccMedicalResult.class, jQueryWrapper);
        return Result.ok(sccMedicalResultIPage.getRecords(),sccMedicalResultIPage.getTotal());
    }
    @RequestMapping("qualify")
    public Result qualifyList(){
        MPJQueryWrapper<SccReportList> jQueryWrapper = new MPJQueryWrapper<>();
        jQueryWrapper.select("COUNT(*) as value,t.Medical_name as name");
        jQueryWrapper.groupBy("t.Medical_name");
        List<Map<String, Object>> maps = reportList.selectMaps(jQueryWrapper);
        return Result.ok(maps);
    }


    @RequestMapping("consumerlist1")
    public Result consumerList1(ConsumerVo1 consumerVo1,Integer page, Integer limit){
        MPJQueryWrapper<SccReportList> jQueryWrapper = new MPJQueryWrapper<>();
        jQueryWrapper.select("b.`Name`,b.Sex,b.Id_card,b.Phone,b.Count_of_test,COUNT(t.Result_id) as renshu,c.Store_name");
        jQueryWrapper.leftJoin("scc_medical_result a on a.Result_id=t.Result_id");
        jQueryWrapper.rightJoin("scc_patient b on b.Patient_id=a.Patient_id");
        jQueryWrapper.rightJoin("scc_drugstore c on a.drugstore_id=c.Store_id");
        jQueryWrapper.groupBy("b.Patient_id");
        jQueryWrapper.eq("t.`status`",1);
        IPage<ConsumerVo3> consumerVo3IPage = reportList.selectJoinPage(new Page<>(page, limit), ConsumerVo3.class, jQueryWrapper);
        int i=1;
        for (ConsumerVo3 consumerVo3 : consumerVo3IPage.getRecords()) {
            consumerVo3.setRenshu(consumerVo3.getRenshu()/consumerVo3.getCountOfTest()*100);
            consumerVo3.setCount(i++);
            consumerVo3.setJilv(consumerVo3.getRenshu()+"%");
        }
        return Result.ok(consumerVo3IPage.getRecords(),consumerVo3IPage.getTotal());
    }

    @RequestMapping("consumerlist2")
    public Result consumer1(Consumer consumer){
        MPJQueryWrapper<SccReportList> jQueryWrapper = new MPJQueryWrapper<>();
        jQueryWrapper.leftJoin("scc_medical_result a on a.Result_id=t.Result_id");
        jQueryWrapper.rightJoin("scc_patient b on b.Patient_id=a.Patient_id");
        jQueryWrapper.select("DATE_FORMAT(t.Update_time,'%m') mun,  t.Medical_name,COUNT(DISTINCT b.Patient_id) as shuLian");
        jQueryWrapper.groupBy("mun,t.Medical_name");
        jQueryWrapper.ne("t.Medical_status",0);
        jQueryWrapper.lt("a.Test_time",new Date());
        jQueryWrapper.gt("a.Test_time",consumer.getTime());
        List<Map<String, Object>> maps = reportList.selectMaps(jQueryWrapper);
        ConsumerVo4 consumerVo4=new ConsumerVo4();
        ArrayList<Object> arrayList=new ArrayList<Object>();
        ArrayList<Object> gluResultList=new ArrayList<Object>();
        ArrayList<Object> hbaicResultList=new ArrayList<Object>();
        ArrayList<Object> uaResultList=new ArrayList<Object>();
        ArrayList<Object> hdiCResultList=new ArrayList<Object>();
        ArrayList<Object> ldlCResultList=new ArrayList<Object>();
        ArrayList<Object> tgResultList=new ArrayList<Object>();
        ArrayList<Object> cholResultList=new ArrayList<Object>();
        ArrayList<Object> tcHdiCResultList=new ArrayList<Object>();
        ArrayList<Object> ketResultList=new ArrayList<Object>();
        ArrayList<Object> sbpResultList=new ArrayList<Object>();
        ArrayList<Object> dbpResultList=new ArrayList<Object>();
        for (Map<String, Object> map : maps) {
            for (String key: map.keySet()){
                String value = map.get(key).toString();
                if (key.equals("mun")){
                    arrayList.add(map.get(key)+"月");
                }else if (key.equals("Medical_name")){
                    if (map.get(key).equals("血糖值")){
                        gluResultList.add(map.get("shuLian"));
                    }else if (map.get(key).equals("血红蛋白")){
                        hbaicResultList.add(map.get("shuLian"));
                    }else if (map.get(key).equals("血尿酸")){
                        uaResultList.add( map.get("shuLian"));
                    }else if (map.get(key).equals("高密度脂蛋白固醇")){
                        hdiCResultList.add( map.get("shuLian"));
                    }else if (map.get(key).equals("低密度脂蛋白固醇")){
                        ldlCResultList.add( map.get("shuLian"));
                    }else if (map.get(key).equals("甘油三脂")){
                        tgResultList.add( map.get("shuLian"));
                    }else if (map.get(key).equals("总蛋白固醇")){
                        cholResultList.add( map.get("shuLian"));
                    }else if (map.get(key).equals("总蛋白固醇/高密度脂蛋白固醇比值")){
                        tcHdiCResultList.add( map.get("shuLian"));
                    }else if (map.get(key).equals("血酮")){
                        ketResultList.add( map.get("shuLian"));
                    }else if (map.get(key).equals("收缩压")){
                        sbpResultList.add( map.get("shuLian"));
                    }else if (map.get(key).equals("舒张压")){
                        dbpResultList.add( map.get("shuLian"));
                    }
                }

            }
        }
        System.out.println(arrayList);
        ArrayList<Object> list1 = CollUtil.distinct(arrayList);
        consumerVo4.setTime(list1.toArray());
        consumerVo4.setCholResult(cholResultList.toArray());
        consumerVo4.setGluResult(gluResultList.toArray());
        consumerVo4.setDbpResult(dbpResultList.toArray());
        consumerVo4.setHbaicResult(hbaicResultList.toArray());
        consumerVo4.setKetResult(ketResultList.toArray());
        consumerVo4.setHdiCResult(hdiCResultList.toArray());
        consumerVo4.setLdlCResult(ldlCResultList.toArray());
        consumerVo4.setSbpResult(sbpResultList.toArray());
        consumerVo4.setTgResult(tgResultList.toArray());
        consumerVo4.setTcHdiCResult(tcHdiCResultList.toArray());
        consumerVo4.setUaResult(uaResultList.toArray());
        return Result.ok(consumerVo4);
    }

    @RequestMapping("month")
    public Result month(Consumer consumer){
        MPJQueryWrapper<SccReportList> jQueryWrapper = new MPJQueryWrapper<>();
        jQueryWrapper.leftJoin("scc_medical_result a on a.Result_id=t.Result_id");
        jQueryWrapper.rightJoin("scc_patient b on b.Patient_id=a.Patient_id");
        jQueryWrapper.select("DATE_FORMAT(t.Update_time,'%d') mun, COUNT(DISTINCT b.Patient_id) as shuLian");
        jQueryWrapper.groupBy("mun");
        jQueryWrapper.eq("DATE_FORMAT(t.Update_time,'%Y-%m')",consumer.getTime());
        List<Month> months = reportList.selectJoinList(Month.class, jQueryWrapper);
        return Result.ok(months);
    }
    @RequestMapping("month1")
    public Result month1(Consumer consumer){
        MPJQueryWrapper<SccMedicalResult> jQueryWrapper = new MPJQueryWrapper<>();
        jQueryWrapper.select("a.Store_name,COUNT(t.Result_id) as jiance,(SELECT a.Store_name FROM scc_drugstore a WHERE a.Store_id=47) as fendian");
        jQueryWrapper.leftJoin("scc_drugstore a ON a.Store_id=t.drugstore_id");
        jQueryWrapper.groupBy("a.Store_id");
        jQueryWrapper.orderByDesc("jiance");
        IPage<Map<String, Object>> mapIPage = medicalResultMapper.selectJoinMapsPage(new Page<>(1, 2), jQueryWrapper);
        int i=0;
        for (Map<String, Object> record : mapIPage.getRecords()) {
            record.put("count",++i);
        }
        System.out.println(mapIPage.getRecords());
        return Result.ok(mapIPage.getRecords(),mapIPage.getTotal());
    }

    @RequestMapping("month2")
    public Result month2(Consumer consumer,Integer page, Integer limit){
        MPJQueryWrapper<SccMedicalResult> jQueryWrapper = new MPJQueryWrapper<>();
        jQueryWrapper.select(" a.store_name,(SELECT a.Store_name FROM scc_drugstore a WHERE a.Store_id=47) as fendian ,COUNT(DISTINCT c.Patient_id) as renshu,COUNT(DISTINCT b.Medical_status=1) as yic");
        jQueryWrapper.leftJoin(" scc_drugstore a ON a.Store_id=t.drugstore_id");
        jQueryWrapper.leftJoin(" scc_report_list b on t.Result_id=b.Result_id");
        jQueryWrapper.leftJoin(" scc_patient c on c.Patient_id=t.Patient_id");
        jQueryWrapper.groupBy("a.Store_id");
        jQueryWrapper.orderByDesc("renshu");
        IPage<Map<String, Object>> mapIPage = medicalResultMapper.selectJoinMapsPage(new Page<>(page, limit), jQueryWrapper);
        int i=0;
        for (Map<String, Object> record : mapIPage.getRecords()) {
            record.put("count",++i);
            Double le= Double.parseDouble(record.get("yic").toString());
            Double le1= Double.parseDouble(record.get("renshu").toString());
            Double le2=le/le1*100;
            record.put("yicl",le2+"%");
        }
        System.out.println(mapIPage.getRecords());
        return Result.ok(mapIPage.getRecords(),mapIPage.getTotal());
    }
    @RequestMapping("month3")
    public  Result month4(Consumer consumer,Integer page, Integer limit){
        MPJQueryWrapper<SccReportList> jQueryWrapper = new MPJQueryWrapper<>();
        jQueryWrapper.select("t.Medical_name,COUNT(*) as cishu,COUNT(t.Medical_status!=0 or null) as yic,COUNT(t.Medical_status=2 or null) di,COUNT(t.Medical_status=3 or null) gao");
        jQueryWrapper.groupBy("t.Medical_name");
        IPage<Map<String, Object>> mapIPage = reportList.selectJoinMapsPage(new Page<>(page, limit), jQueryWrapper);
        for (Map<String, Object> record : mapIPage.getRecords()) {
            Double le= Double.parseDouble(record.get("yic").toString());
            Double le1= Double.parseDouble(record.get("cishu").toString());
            Double le2=le/le1*100;
            record.put("yicl",le2+"%");
        }
        return Result.ok(mapIPage.getRecords(),mapIPage.getTotal());
    }






}
